import tkinter as tk
from PIL import Image, ImageTk, ImageDraw, ImageFont
import random
from .Shared import *

player = shareddata.get_player()

class PageZhandoushuang(tk.Frame):
    class GameObject:
        def __init__(self, x, y, w, h, mhp, nhp):
            self.x = x
            self.y = y
            self.w = w
            self.h = h
            self.mhp = mhp
            self.nhp = nhp 
        def rect(self):
            return (self.x, self.y, self.x+self.w, self.y+self.h)

    def __init__(self, parent):
        super().__init__(parent)
        self.configure(bg="white", width=1200, height=720)
        self.pack_propagate(False)
        self.bind("<Expose>", lambda event: self.on_raise(event, parent))
        self.parent = parent
        global player
        player = shareddata.get_player()
        self.key = { "a": 0, "d": 0, "w": 0, "s": 0, "j": 0, "i": 0}
        self.chapter = shareddata.get_chapter()  
        # 游戏状态管理
        self.game_state = "start"  # start/fighting/victory/gameover
        self.is_paused = False   
        self.character = player["characterlist"]["0"]
        self.player_pos = [300, 360]
        self.enemies = []
        self.bullets = []
        self.score = 0
        self.health = (self.character["Bhp"]+self.character["equip"]["clothes"]["Bhp"])*(1+self.character["Zhp"]+self.character["equip"]["core"]["Zhp"])
        self.atk = int((self.character["Batk"] + self.character["equip"]["weapon"]["Batk"]) * (1 + self.character["Zatk"] + self.character["equip"]["enchant"]["Zatk"]))
        self.ele = int((self.character["Bele"] + self.character["equip"]["weapon"]["Bele"] + self.character["equip"]["clothes"]["Bele"] + self.character["equip"]["shoes"]["Bele"]) * (1 + self.character["Zele"] + self.character["equip"]["enchant"]["Zele"] + self.character["equip"]["core"]["Zele"] + self.character["equip"]["medal"]["Zele"]))
        self.mhp = self.health
        self.result_btn = None
        self.number = []
        # 加载图形资源
        self.picture = {
            "PageZhandoushuang": shareddata.get_picture("PageZhandoushuang"),
            "Resources": shareddata.get_picture("Resources")
        }
        # 双缓冲画布
        self.buffer_image = Image.new("RGBA", (1200, 720), (255, 255, 255, 0))
        self.canvas = tk.Canvas(self, width=1200, height=720, highlightthickness=0)
        self.canvas.place(x=0, y=0)
        self.canvas.bind("<Button-1>", self.start_game)
        # 暂停按钮
        self.pause_btn = tk.Button(self.canvas, text="esc", command=self.toggle_pause, font=("Arial", 20), bg="#FF5555", fg="white", bd=0, relief="flat")
        self.pause_btn.place(x=1150, y=10, anchor="ne")
        # 绑定键盘事件
        self.bind_keys()
        self.update_buffer(parent)

    def toggle_pause(self):
        if self.game_state != "fighting":
            return  
        self.is_paused = not self.is_paused
        if self.is_paused:
            self.show_pause_menu()
            self.pause_btn.config(text="▶")
        else:
            self.hide_pause_menu()
            self.pause_btn.config(text="⏸")

    def show_pause_menu(self):
        self.pause_overlay = tk.Canvas(self.canvas, width = 300, height = 400, bg = "white", highlightthickness = 0)
        self.pause_overlay.place(x = 450, y = 160)
        pause_panel = tk.Canvas(self.pause_overlay, width = 400, height = 300, bg = "#333333", highlightthickness = 0)
        pause_panel.place(relx = 0.5, rely = 0.5, anchor = "center")
        pause_panel.create_text(200, 60, text = "游戏暂停", fill = "white",font = ("Arial", 24, "bold"))
        btn_continue = tk.Button(pause_panel, text = "继续游戏", command = self.toggle_pause, bg = "#4CAF50", fg = "white", font = ("Arial", 16), width = 15, height = 2)
        btn_continue.place(x = 100, y = 120)
        btn_menu = tk.Button(pause_panel, text = "返回主菜单", command = self.back_to_menu, bg = "#F44336", fg = "white", font = ("Arial", 16), width = 15, height = 2)
        btn_menu.place(x = 100, y = 200)

    def hide_pause_menu(self):
        if hasattr(self, 'pause_overlay') and self.pause_overlay.winfo_exists():
            self.pause_overlay.destroy()

    def bind_keys(self):
        self.parent.bind("<KeyPress>", self.handle_keyP)
        self.parent.bind("<KeyRelease>", self.handle_keyR)

    def unbind_keys(self):
        self.parent.unbind("<KeyPress>")
        self.parent.unbind("<KeyRelease>")

    def check_collision(self, rect1, rect2):
        return not ((rect1[2] < rect2[0]) or (rect1[0] > rect2[2]) or (rect1[3] < rect2[1]) or (rect1[1] > rect2[3]))

    def game_loop(self):
        if self.game_state != "fighting" or self.is_paused:
            self.after(50, self.game_loop)
            return    
        # 状态更新
        speed = 30
        if self.key['a']:
            self.player_pos[0] = max(0, self.player_pos[0]-speed)
        if self.key['d']:
            self.player_pos[0] = min(1120, self.player_pos[0]+speed)
        if self.key['w']:
            self.player_pos[1] = max(130, self.player_pos[1]-speed)
        if self.key['s']:
            self.player_pos[1] = min(640, self.player_pos[1]+speed)
        if self.key['i']:
            for enemy in self.enemies[:]:
                if abs(enemy.y + 25 - (self.player_pos[1] +40)) <= 300:
                    enemy.nhp -= self.atk * self.ele
                    self.number.append([enemy.x, enemy.y-20, self.atk * self.ele, 10])
                    if(enemy.nhp <= 0):
                        self.enemies.remove(enemy)
                        self.score += 100      
        elif self.key['j']:
            self.bullets.append(self.GameObject(
                self.player_pos[0]+80, self.player_pos[1]+40, 20, 5, 0, 0))       
        # 更新子弹位置
        for bullet in self.bullets[:]:
            bullet.x += 15
            if bullet.x > 1300:
                self.bullets.remove(bullet)          
        # 更新敌人位置
        for enemy in self.enemies[:]:
            enemy.x -= 5
            if enemy.x < -100:
                self.enemies.remove(enemy)           
        # 生成新敌人
        if random.random() < 0.1:
            self.enemies.append(self.GameObject(
                1300, random.randint(200, 670), 50, 50, 
                20000 * int(player['fight'].split("-")[0]) + 4000 * int(player['fight'].split("-")[1]), 
                20000 * int(player['fight'].split("-")[0]) + 4000 * int(player['fight'].split("-")[1])))    
        # 碰撞检测
        player_rect = (self.player_pos[0], self.player_pos[1], self.player_pos[0]+80, self.player_pos[1]+80)              
        # 子弹与敌人碰撞
        for bullet in self.bullets[:]:
            flag = False
            for enemy in self.enemies[:]:
                if self.check_collision(bullet.rect(), enemy.rect()) and not flag:
                    flag = True
                    self.bullets.remove(bullet)
                    enemy.nhp -= self.atk * self.ele
                    self.number.append([enemy.x, enemy.y-20, self.atk * self.ele, 10])
                    if(enemy.nhp <= 0):
                        self.enemies.remove(enemy)
                        self.score += 100           
        # 玩家与敌人碰撞
        for enemy in self.enemies[:]:
            if self.check_collision(player_rect, enemy.rect()):
                self.health = max(0, self.health - 10)
                if self.health <= 0:
                    self.game_state = "gameover"
                    self.show_gameover()                       
        # 胜利条件检测
        if self.score >= 1000:
            self.game_state = "victory"
            self.show_victory()      
        self.update_buffer(self.parent)
        self.after(50, self.game_loop)

    def draw_to_buffer(self, buffer_image, parent):
        global player
        player = shareddata.get_player()
        draw = ImageDraw.Draw(buffer_image)
        draw.rectangle([0, 0, 1200, 720], fill="#FFFFFF")
        if self.game_state == "start":
            font = ImageFont.truetype("arial.ttf", 40)
            buffer_image.paste(self.picture["PageZhandoushuang"]["Tip"][0], (0, 0), self.picture["PageZhandoushuang"]["Tip"][0])
        elif self.game_state == "fighting":
            # 绘制顶板
            buffer_image.paste(self.picture["PageZhandoushuang"]["TopFrame"][0], (510, 0), self.picture["PageZhandoushuang"]["TopFrame"][0]) 
            draw.text((600 - int(len(player["fight"]) / 2 * 16), 15), player["fight"], fill = "black", font = shareddata.get_font(30))
            draw.text((600 - int(len("score") / 2 * 18), 45), "score", fill = "black", font = shareddata.get_font(30))
            draw.text((600 - int(len(str(self.score)) / 2 * 20), 75), str(self.score), fill = "black", font = shareddata.get_font(30))
            
            # 绘制属性面板
            buffer_image.paste(self.picture["PageZhandoushuang"]["PanelFrame"][0], (0, 0), self.picture["PageZhandoushuang"]["PanelFrame"][0]) 
            draw.rectangle([110, 28, 110 + int(220 * self.health/self.mhp), 43], fill = "green")   
            draw.text((350, 20), f"{int(self.health)}/{int(self.mhp)}", fill = "#FFFFFF", font = shareddata.get_font(25))
            draw.text((100, 50), f"atk:{self.atk}", fill="#FFFFFF", font = shareddata.get_font(25))
            draw.text((240, 50), f"def:{int((self.character['Bdef'] + self.character['equip']['shoes']['Bdef']) * (1 + self.character['Zdef'] + self.character['equip']['medal']['Zdef']))}", fill="#FFFFFF", font = shareddata.get_font(25))
            draw.text((380, 50), f"ele:{self.ele}", fill="#FFFFFF", font = shareddata.get_font(25))
            
            # 绘制玩家
            buffer_image.paste(self.picture["PageZhandoushuang"]["Kiana"][0], (self.player_pos[0], self.player_pos[1]), self.picture["PageZhandoushuang"]["Kiana"][0]) 
            
            # 绘制敌人
            for enemy in self.enemies:
                buffer_image.paste(self.picture["PageZhandoushuang"]["Enemy"][0], (enemy.x, enemy.y), self.picture["PageZhandoushuang"]["Enemy"][0]) 
                draw.rectangle([enemy.x, enemy.y-10, enemy.x+50, enemy.y-5], fill="black")
                draw.rectangle([enemy.x, enemy.y-10, enemy.x+int(50*enemy.nhp/enemy.mhp), enemy.y-5], fill="green")
                draw.text((enemy.x, enemy.y-23), f"hp:{enemy.nhp}", fill="#FF0000", font = shareddata.get_font(13))
                #draw.rectangle(enemy.rect(), fill="#FF0000")
                
            # 绘制子弹
            for bullet in self.bullets:
                buffer_image.paste(self.picture["PageZhandoushuang"]["Zd"][0], (bullet.x, bullet.y), self.picture["PageZhandoushuang"]["Zd"][0]) 
                
            if self.key['i']:
                buffer_image.paste(self.picture["PageZhandoushuang"]["Dz"][0], (self.player_pos[0] + 80, self.player_pos[1] + 40 - 300), self.picture["PageZhandoushuang"]["Dz"][0]) 
            
            # 绘制伤害数字
            for item in self.number:
                draw.text((item[0], item[1]), f"-{item[2]}", fill = "#000000", font = shareddata.get_font(20-item[3]))
                item[1] -= 10
                item[3] -= 1
                if(item[3] <= 0):
                    self.number.remove(item)
                    
        elif self.game_state == "victory":
            buffer_image.paste(self.picture["PageZhandoushuang"]["Victory"][0], (350,60), self.picture["PageZhandoushuang"]["Victory"][0]) 
            buffer_image.paste(self.picture["Resources"]["Crystal"][0], (585,350), self.picture["Resources"]["Crystal"][0]) 
            string = "+" + str(self.chapter[(eval(player['fight'].split('-')[0]) - 1) * 5 + eval(player['fight'].split('-')[1]) - 1]['rewards']['crystal'])
            draw.text((600 - len(string) * 13, 390), string, fill = "#FF0000", font = ImageFont.truetype("arial.ttf", 50))
            buffer_image.paste(self.picture["Resources"]["Coin"][0], (585,450), self.picture["Resources"]["Coin"][0]) 
            string = "+" + str(self.chapter[(eval(player['fight'].split('-')[0]) - 1) * 5 + eval(player['fight'].split('-')[1]) - 1]['rewards']['coin'])
            draw.text((600 - len(string) * 13, 490), string, fill = "#FF0000", font = ImageFont.truetype("arial.ttf", 50))
            #draw.text((500, 300), "win!", fill = "#FF0000",
            #         font = ImageFont.truetype("arial.ttf", 48))
        elif self.game_state == "gameover":
            draw.text((550, 300), "lose!", fill = "#FF0000",
                     font = ImageFont.truetype("arial.ttf", 48))

    # ...（保持其他方法 handle_keyP、handle_keyR、start_game、show_victory、show_gameover 不变）...
    def handle_keyP(self, event):
        if self.game_state != "fighting":
            return
        speed = 30
        if event.char == 'a':
            self.key['a'] = 1
        if event.char == 'd':
            self.key['d'] = 1
        if event.char == 'w':
            self.key['w'] = 1
        if event.char == 's':
            self.key['s'] = 1
        if event.char == 'j':
            self.key['j'] = 1
        if event.char == 'i':
            self.key['i'] = 1

    def handle_keyR(self, event):
        if self.game_state != "fighting":
            return
        speed = 30
        if event.char == 'a':
            self.key['a'] = 0
        if event.char == 'd':
            self.key['d'] = 0
        if event.char == 'w':
            self.key['w'] = 0
        if event.char == 's':
            self.key['s'] = 0
        if event.char == 'j':
            self.key['j'] = 0
        if event.char == 'i':
            self.key['i'] = 0

    def start_game(self, event):
        if self.game_state == "start":
            self.game_state = "fighting"
            self.canvas.unbind("<Button-1>")
            self.game_loop()

    def show_victory(self):
        global player
        player = shareddata.get_player()
        player["crystal"] += self.chapter[(eval(player['fight'].split('-')[0]) - 1) * 5 + eval(player['fight'].split('-')[1]) - 1]['rewards']['crystal']
        player["coin"] += self.chapter[(eval(player['fight'].split('-')[0]) - 1) * 5 + eval(player['fight'].split('-')[1]) - 1]['rewards']['coin']
        shareddata.set_player(player)
        self.chapter[(eval(player['fight'].split('-')[0]) - 1) * 5 + eval(player['fight'].split('-')[1]) - 1]['rewards']['crystal']
        self.result_btn = tk.Button(self, text = "返回菜单", command = self.back_to_menu)
        self.result_btn.place(x = 570, y = 600)

    def show_gameover(self):
        shareddata.set_player(player)
        self.result_btn = tk.Button(self, text = "返回菜单", command = self.back_to_menu)
        self.result_btn.place(x = 570, y = 600)

    def back_to_menu(self):
        shareddata.set_player(player)
        self.hide_pause_menu()
        self.is_paused = False
        self.parent.show_frame("PageFight")
        self.reset_game()

    def restart_game(self):
        self.reset_game()
        self.game_state = "start"
        self.canvas.bind("<Button-1>", self.start_game)
        if self.result_btn and self.result_btn.winfo_exists():
            self.result_btn.destroy()
            self.result_btn = None
        self.update_buffer(self.parent)

    def reset_game(self):
        global player
        player = shareddata.get_player()  
        self.player_pos = [600, 360]
        self.enemies.clear()
        self.bullets.clear()
        self.number.clear()
        self.score = 0
        self.health = (self.character["Bhp"]+self.character["equip"]["clothes"]["Bhp"])*(1+self.character["Zhp"]+self.character["equip"]["core"]["Zhp"])
        self.atk = int((self.character["Batk"] + self.character["equip"]["weapon"]["Batk"]) * (1 + self.character["Zatk"] + self.character["equip"]["enchant"]["Zatk"]))
        self.ele = int((self.character["Bele"] + self.character["equip"]["weapon"]["Bele"] + self.character["equip"]["clothes"]["Bele"] + self.character["equip"]["shoes"]["Bele"]) * (1 + self.character["Zele"] + self.character["equip"]["enchant"]["Zele"] + self.character["equip"]["core"]["Zele"] + self.character["equip"]["medal"]["Zele"]))
        self.mhp = self.health
        self.key = {
            "a": 0,
            "d": 0,
            "w": 0,
            "s": 0,
            "j": 0,
            "i": 0
        }
        self.is_paused = False
        self.pause_btn.config(text = "⏸")
        
    def update_buffer(self, parent):
        self.buffer_image.paste((255, 255, 255, 0), [0, 0, 1200, 720])
        self.draw_to_buffer(self.buffer_image, parent)
        self.photo_buffer = ImageTk.PhotoImage(self.buffer_image)
        self.canvas.create_image(0, 0, image=self.photo_buffer, anchor=tk.NW)

    def on_raise(self, event, parent):
        global player
        player = shareddata.get_player()
        self.restart_game()
        self.update_buffer(parent)